//
//  YWNetWorkTool.swift
//  AiSaiSwiftUIDemo
//
//  Created by 陈友文 on 2023/6/5.
//

import Foundation
import Alamofire
import ProgressHUD
import Toaster


class YWNetworkTool:NSObject{
#if DEBUG
    private let base_url = "http://192.168.1.120:6011/"
//    private let base_url = "http://106.54.216.250:6011/"
#else
//    private let base_url = "http://192.168.0.48:6010/"
    private let base_url = "http://106.54.216.250:6011/"
#endif
    private static let shareManager = YWNetworkTool()
    
    public class func share() -> YWNetworkTool {
        AF.sessionConfiguration.timeoutIntervalForRequest = 60
        return shareManager
    }
    
    typealias SuccessBlock<T> = (_ res:T) -> Void
    typealias FailBlock = ((Any?, String) -> Void)
    
}

extension YWNetworkTool {
    /// 普通htpp请求
    /// - Parameters:
    ///   - url: url
    ///   - parameters: 入参 遵守Codable协议
    ///   - of: 返回值遵守Codable协议
    ///   - tips: loading提示
    ///   - method: 请求方式
    ///   - headers: 请求头
    ///   - encoder: 入参解码类型 默认JSONParameterEncoder
    ///   - successBlock: 成功回调
    ///   - failBlock: 失败回调
    func request<T:Encodable,Q:Decodable>(
        url:String,
        parameters:T,
        of:Q.Type,
        tips:String? = nil,
        method:HTTPMethod = .post,
        //        headers:HTTPHeaders? = nil,
        encoder:ParameterEncoder = JSONParameterEncoder.default,
        successBlock:@escaping SuccessBlock<Q>,
        failBlock:@escaping FailBlock) {
            if let tips = tips {
//                ProgressHUD.show(tips,interaction: false)
                ProgressHUD.animate(tips, interaction: false)
            }
            // headers处理
            var requestHeaders = HTTPHeaders()
            if let token = UserDefaults.standard.value(forKey: "token") {
                requestHeaders.add(name: "Authorization", value: "Bearer \(token)")
            }
            
            AF.request(
                base_url + url,
                method: method,
                parameters: parameters,
                encoder: encoder,
                headers: requestHeaders
            )
            .validate() // 验证200 - 299
            .responseDecodable(of:of) { response in
                guard let _ = response.value else {
//                    ProgressHUD.show("错误",icon: .failed,delay:2.0)
//                    ProgressHUD.animate("错误", <#T##type: AnimationType##AnimationType#>, interaction: <#T##Bool#>)
                    YWToast.show(text: "错误", duration: 2.0)
                    failBlock(response.error?.responseCode,
                              response.error?.localizedDescription ?? "error")
                    return
                }
                switch response.result {
                case .success(let value):
                    ProgressHUD.dismiss()
                    successBlock(value)
                case .failure(let error):
//                    ProgressHUD.show("错误",icon: .failed,delay:2.0)
                    YWToast.show(text: "错误", duration: 2.0)
                    failBlock(error,"error")
                }
            }
        }
    
    func requestJson(
        url:String,
        parameters:Parameters?,
        method:HTTPMethod = .post,
        tips:String? = nil,
        encoding:ParameterEncoding = JSONEncoding.default,
        headers:HTTPHeaders? = nil,
        responseSuccessBlock:@escaping ((Any) -> Void),
        responseFailBlock:@escaping ((Any,String) -> Void)
        
    ) {
        
        if let tips = tips {
//            ProgressHUD.show(tips,interaction: false)
            ProgressHUD.animate(tips, interaction: false)
        }
        
        var header = HTTPHeaders()
        header = headers ?? HTTPHeaders()
        if let token = UserDefaults.standard.value(forKey: kUserToken) {
            header.add(name: "Authorization", value: "\(token)")
        }
        
        AF.request(base_url + url, method: method, parameters:parameters, encoding: JSONEncoding.default, headers: header).responseJSON {  response in
            print("url: \(url)")
            guard let _ = response.value else {
//                ProgressHUD.show("错误",icon: .failed,delay:2.0)
                ProgressHUD.dismiss()
//                YWToast.show(text: "错误", duration: 2.0)
                responseFailBlock(response.error?.responseCode,response.error?.localizedDescription ?? "error")
                return
            }
            
            switch response.result {
            case .success(let value):
                ProgressHUD.dismiss()
                
                if let json = value as? [String:Any]{
                    responseSuccessBlock(json)
                } else {
                    responseFailBlock(response.error?.responseCode,response.error?.localizedDescription ?? "error")
                }
            case .failure(let error):
//                ProgressHUD.show("错误",icon: .failed,delay:2.0)                
                ProgressHUD.dismiss()
//                YWToast.show(text: "错误", duration: 2.0)
                responseFailBlock(error,"error")
            }
        }
    }
}


